package com.ljh.onlinetest.controller.admin;

import com.github.pagehelper.PageInfo;
import com.ljh.onlinetest.base.BaseApiController;
import com.ljh.onlinetest.base.RestResponse;
import com.ljh.onlinetest.domain.TaskExam;
import com.ljh.onlinetest.service.TaskExamService;
import com.ljh.onlinetest.service.TextContentService;
import com.ljh.onlinetest.utils.DateTimeUtil;
import com.ljh.onlinetest.utils.PageInfoHelper;
import com.ljh.onlinetest.viewmodel.admin.task.TaskPageRequestVM;
import com.ljh.onlinetest.viewmodel.admin.task.TaskPageResponseVM;
import com.ljh.onlinetest.viewmodel.admin.task.TaskRequestVM;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * @author 余一
 * @date 2022/2/15  21:50
 */
@RestController("AdminTaskController")
@RequestMapping("/api/admin/task")
public class TaskController extends BaseApiController {

    private final TaskExamService taskExamService;

    @Autowired
    public TaskController(TaskExamService taskExamService) {
        this.taskExamService = taskExamService;
    }

    @PostMapping("/page")
    public RestResponse<PageInfo<TaskPageResponseVM>> page(@RequestBody TaskPageRequestVM model){
        PageInfo<TaskExam> taskExamPageInfo = taskExamService.page(model);
        PageInfo<TaskPageResponseVM> taskPageResponseVmPageInfo = PageInfoHelper.copyMap(taskExamPageInfo, taskExam -> {
            TaskPageResponseVM taskPageResponseVM = modelMapper.map(taskExam,TaskPageResponseVM.class);
            taskPageResponseVM.setCreateTime(DateTimeUtil.dateFormat(taskExam.getCreateTime()));
            return taskPageResponseVM;
        });
        return RestResponse.ok(taskPageResponseVmPageInfo);
    }

    @PostMapping("/select/{id}")
    public RestResponse<TaskRequestVM> select(@PathVariable Integer id){
        TaskRequestVM vm = taskExamService.taskExamToVM(id);
        return RestResponse.ok(vm);
    }

    @PostMapping("/edit")
    public RestResponse<TaskRequestVM> edit(@RequestBody @Valid TaskRequestVM model){
        taskExamService.edit(model,getCurrentUser());
        TaskRequestVM vm = taskExamService.taskExamToVM(model.getId());
        return RestResponse.ok(vm);
    }

    @PostMapping("/delete/{id}")
    public RestResponse delete(@PathVariable Integer id){
        taskExamService.deleteById(id);
        return RestResponse.ok();
    }
}
